package org.examples.java.lang;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.CountDownLatch;

import org.junit.Test;

public class ThreadLocalTest {

    private ThreadLocal<String> localString = new ThreadLocal<String>();

    @Test
    public void testGetSetInSingleThread() {
        localString.set("AAA");
        assertEquals("AAA", localString.get());
        localString.remove();
        assertEquals(null, localString.get());
    }


    @Test
    public void testTwoThreads() throws InterruptedException {
        localString.set("1");

        final CountDownLatch latch = new CountDownLatch(1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                assertEquals(null, localString.get());
                localString.set("2");
                latch.countDown();
            }
        }).start();

        latch.await();
        assertEquals("1", localString.get());
    }

}
